package com.yonyou.brigade.third_parties.didi.util;

import com.yonyou.ybzboot.starter.mail.model.Email;
import freemarker.template.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.internet.MimeMessage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

@Component
public class EmailUtil {
    private static final Logger logger = LoggerFactory.getLogger(EmailUtil.class);

    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    public Configuration configuration;
    @Value("${spring.mail.username}")
    public String USER_NAME;

    @Value("${didi.emailImage.brigde_didi_email_tail}")
    private String tailImageUrl;

    @Value("${didi.emailImage.brigde_didi_email_logo}")
    private String logoImageUrl;


    public void sendAttachment(Email mail, String itineraryString, String invoiceString) throws Exception{
        MimeMessage message = this.mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(this.USER_NAME);
        helper.setTo(mail.getEmail());
        helper.setSubject(mail.getSubject());
        helper.setText(getHtml(), true);

        DataSource invoiceSource = new URLDataSource(new URL(invoiceString));
        helper.addAttachment("滴滴电子发票.pdf", invoiceSource);
        DataSource itinerarySource = new URLDataSource(new URL(itineraryString));
        helper.addAttachment("滴滴出行行程报销单.pdf", itinerarySource);
        this.mailSender.send(message);
    }

    public String getHtml(){
        StringBuilder builder = new StringBuilder();
        builder.append("<html><body>");
        builder.append("<div>");
        builder.append("<img src=\"" + logoImageUrl + "\" >");
        builder.append("<span style=\"display: block;float: right;margin-left: 10px\">");
        builder.append("<span style=\"display: block;font-weight: bold;text-align: center;\">滴滴电子发票服务</span>");
        builder.append("<span style=\"display: block;text-align: center;\">400-000-0999<span>");
        builder.append("</span>");
        builder.append("</div>");
        builder.append("<hr style=\"clear: both;margin-top: 20px;margin-bottom: 20px\">");
        builder.append("<div>");
        builder.append("<span style=\"display: block;max-width: 100%; text-align: center;font-weight: bold;font-size: 30\">您申请的电子发票已开出</span>");
        builder.append("<span style=\"display: block;max-width: 100%; text-align: center;\">请点击附件查看并核对发票明细</span>");
        builder.append("</div>");
        builder.append("<hr style=\"clear: both;margin-top: 30px;margin-bottom: 20px\">");
        builder.append("<span style=\"display: block;font-weight: bold;margin-top: 10px\">尊敬的滴滴乘客:</span>");
        builder.append("<span style=\"display: block;margin-top: 10px\">感谢您使用滴滴出行并选择开票业务，查看发票对应的行程单请单击附件。您可以在APP-我的钱包-开票-开票历史中查看最新的开票进度。</span>");
        builder.append("<img style=\"display: block;width: 100%;margin-top: 30px\" src=\"" + tailImageUrl + "\">");
        builder.append("</body></html>");
        return builder.toString();
    }

    public File downloadFile(String urlPath, String downloadDir) {
        File file = null;
        try {
            // 统一资源
            URL url = new URL(urlPath);
            // 连接类的父类，抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            //设置超时
            httpURLConnection.setConnectTimeout(1000*5);
            //设置请求方式，默认是GET
            httpURLConnection.setRequestMethod("GET");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打开到此 URL引用的资源的通信链接（如果尚未建立这样的连接）。
            httpURLConnection.connect();
            // 文件大小
            int fileLength = httpURLConnection.getContentLength();

            // 控制台打印文件大小
            System.out.println("您要下载的文件大小为:" + fileLength / (1024 * 1024) + "MB");

            // 建立链接从请求中获取数据
            URLConnection con = url.openConnection();
            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
            // 指定文件名称(有需求可以自定义)
            String fileFullName = "aaaf.pdf";
            // 指定存放位置(有需求可以自定义)
            String path = fileFullName;
            file = new File(path);
            // 校验文件夹目录是否存在，不存在就创建一个目录
//            if (!file.getParentFile().exists()) {
//                file.getParentFile().mkdirs();
//            }

            OutputStream out = new FileOutputStream(file);
            int size = 0;
            int len = 0;
            byte[] buf = new byte[2048];
            while ((size = bin.read(buf)) != -1) {
                len += size;
                out.write(buf, 0, size);
            }
            // 关闭资源
            bin.close();
            out.close();
            System.out.println("文件下载成功！");
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("文件下载失败！");
        } finally {
            return file;
        }

    }
}
